<template>
  <div class="login-bg">
    <el-card class="login-card">
      <div class="login-header">
        <img src="../assets/logo.png" alt="logo" class="login-logo" />
        <div class="login-desc">便捷、专业的在线考试平台</div>
      </div>
      <el-tabs v-model="currentForm" stretch>
        <el-tab-pane label="登录" name="login">
          <el-form
            :model="loginData"
            :rules="loginRules"
            ref="loginFormRef"
            label-position="top"
            @submit.prevent
          >
            <el-form-item prop="username" label="用户名/手机号/邮箱">
              <el-input v-model="loginData.username" autocomplete="username" />
            </el-form-item>
            <el-form-item prop="password" label="密码">
              <el-input
                v-model="loginData.password"
                type="password"
                autocomplete="current-password"
                show-password
              />
            </el-form-item>
            <div class="forget-password">
              <el-checkbox v-model="loginData.remember">记住账号</el-checkbox>
              <el-link type="primary" href="#">忘记密码？</el-link>
            </div>
            <el-form-item>
              <el-button type="primary" style="width: 100%" @click="handleLogin"
                >立即登录
              </el-button>
            </el-form-item>
          </el-form>
          <div style="text-align: center; color: #aaa; margin: 16px 0 8px 0">
            其他登录方式
          </div>
          <div style="display: flex; justify-content: center; gap: 16px">
            <el-button circle
              ><el-icon><ChromeFilled /></el-icon
            ></el-button>
            <el-button circle
              ><el-icon><Eleme /></el-icon
            ></el-button>
            <el-button circle
              ><el-icon><ElemeFilled /></el-icon
            ></el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="注册" name="register">
          <el-tabs
            v-model="registerType"
            stretch
            tab-position="top"
            class="login-register-tabs"
          >
            <el-tab-pane label="手机号注册" name="phone"></el-tab-pane>
            <el-tab-pane label="邮箱注册" name="email"></el-tab-pane>
          </el-tabs>
          <el-form
            :model="registerData"
            :rules="registerRules"
            ref="registerFormRef"
            label-position="left"
            @submit.prevent
            label-width="90px"
          >
            <el-form-item prop="username" label="用户名">
              <el-input
                v-model="registerData.username"
                autocomplete="username"
              />
            </el-form-item>
            <el-form-item
              v-if="registerType === 'phone'"
              prop="phone"
              label="手机号"
            >
              <el-input v-model="registerData.phone" autocomplete="tel">
                <template #append>
                  <el-button
                    :disabled="phoneCountdown > 0"
                    @click="sendPhoneCode"
                    >{{
                      phoneCountdown > 0 ? `${phoneCountdown}s` : "发送验证码"
                    }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item
              v-if="registerType === 'phone'"
              prop="code"
              label="验证码"
            >
              <el-input v-model="registerData.code" maxlength="6" />
            </el-form-item>
            <el-form-item
              v-if="registerType === 'email'"
              prop="email"
              label="邮箱"
            >
              <el-input v-model="registerData.email" autocomplete="email">
                <template #append>
                  <el-button
                    style="padding: 1px"
                    :disabled="emailCountdown > 0"
                    @click="sendEmailCode"
                    >{{
                      emailCountdown > 0 ? `${emailCountdown}s` : "发送验证码"
                    }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item
              v-if="registerType === 'email'"
              prop="code"
              label="验证码"
            >
              <el-input v-model="registerData.code" maxlength="6" />
            </el-form-item>
            <el-form-item prop="password" label="设置密码">
              <el-input
                v-model="registerData.password"
                type="password"
                autocomplete="new-password"
                show-password
              />
            </el-form-item>
            <el-form-item prop="confirmPassword" label="确认密码">
              <el-input
                v-model="registerData.confirmPassword"
                type="password"
                autocomplete="new-password"
                show-password
              />
            </el-form-item>
          </el-form>
          <div
            style="
              margin-top: 8px;
              display: flex;
              flex-direction: column;
              align-items: flex-start;
            "
          >
            <el-checkbox
              v-model="registerData.agreement"
              style="margin-bottom: 16px"
              ><span style="display: flex"
                >我已阅读并同意
                <el-link type="primary" href="#">《用户协议》</el-link>
                和
                <el-link type="primary" href="#">《隐私政策》</el-link></span
              >
            </el-checkbox>
            <el-button
              type="primary"
              style="width: 100%"
              @click="handleRegister"
              >立即注册
            </el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div class="login-footer">
        <div>
          <el-select v-model="language" size="small" style="width: 120px">
            <el-option label="简体中文" value="zh-CN" />
            <el-option label="English" value="en" />
          </el-select>
        </div>
        <div>
          <el-link type="info" href="#">用户协议</el-link>
          <el-link type="info" href="#" style="margin-left: 8px"
            >隐私政策
          </el-link>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { computed, ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { userApi } from "../api/userApi.js";
import { useUserStore } from "../store";
import { ChromeFilled, Eleme, ElemeFilled } from "@element-plus/icons-vue";

const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);

const router = useRouter();
const loginFormRef = ref(null);
const registerFormRef = ref(null);

const currentForm = ref("login");
const registerType = ref("phone");
const language = ref("zh-CN");
const phoneCountdown = ref(0);
const emailCountdown = ref(0);

// 登录表单数据
const loginData = reactive({
  username: "",
  password: "",
});

// 注册表单数据
const registerData = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  email: "",
  phone: "",
  code: "",
  agreement: false,
});

// 登录校验规则
const loginRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
};

// 注册校验规则
const registerRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 6, max: 6, message: "长度为6个数字", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== registerData.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
};

const startCountdown = (type) => {
  if (type === "phone") {
    phoneCountdown.value = 60;
    const timer = setInterval(() => {
      phoneCountdown.value--;
      if (phoneCountdown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  } else {
    emailCountdown.value = 60;
    const timer = setInterval(() => {
      emailCountdown.value--;
      if (emailCountdown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  }
};

const sendPhoneCode = async () => {
  if (!registerData.phone) {
    ElMessage.error("请输入手机号码");
    return;
  }
  if (!/^1[3-9]\d{9}$/.test(registerData.phone)) {
    ElMessage.error("请输入正确的手机号码");
    return;
  }
  await userApi.sendCode({
    Phone: registerData.phone,
  });
  startCountdown("phone");
  ElMessage.success("验证码已发送");
};

const sendEmailCode = async () => {
  if (!registerData.email) {
    ElMessage.error("请输入邮箱地址");
    return;
  }
  if (!/^[^\s@]+@[^ -\s@]+\.[^\s@]+$/.test(registerData.email)) {
    ElMessage.error("请输入正确的邮箱地址");
    return;
  }
  await userApi.sendCode({
    Email: registerData.email,
  });
  startCountdown("email");
  ElMessage.success("验证码已发送");
};

const handleLogin = async () => {
  if (!loginFormRef.value) return;
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await userApi.login({
          Username: loginData.username,
          Password: loginData.password,
        });
        userStore.setToken(res.result.Token);
        userStore.setUserInfo(res.result);
        ElMessage.success("登录成功");
        router.push("/");
      } catch (error) {
        console.log(error)
      }
    }
  });
};

const handleRegister = async () => {
  console.log(registerData.agreement);

  if (!registerFormRef.value) return;
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      if (registerData.agreement) {
        try {
          await userApi.register({
            Username: registerData.username,
            Password: registerData.password,
            Email: registerData.email,
            Phone: registerData.phone,
            Code: registerData.code,
          });
          ElMessage.success("注册成功，请登录");
          currentForm.value = "login";
        } catch (error) {
          ElMessage.error("注册失败");
        }
      } else {
        ElMessage.info("请勾选用户协议和隐私政策！");
      }
    }
  });
};
</script>

<style>
.login-bg {
  min-height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("../assets/images/back.png") no-repeat center center fixed;
  background-size: cover;
}

.login-card {
  width: 360px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.15);
  padding: 32px 28px;
}

.login-header {
  text-align: center;
  margin-bottom: 24px;
}

.login-logo {
  height: 48px;
  margin-bottom: 8px;
  display: inline-block;
}

.login-desc {
  color: #888;
  font-size: 18px;
  margin-bottom: 8px;
}

.login-footer {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  color: #888;
}

.login-register-tabs {
  margin-bottom: 8px;
}

.forget-password {
  align-items: center;
  display: flex;
  flex: 1;
  font-size: var(--font-size);
  line-height: 32px;
  min-width: 0;
  position: relative;
  justify-content: space-between;
  margin-bottom: 18px;
}
</style>
